<?php

namespace V1\Model;

use Think\Exception;
use Think\Model;
use Common\Common\Tools;

class MessageModel extends Model
{
    protected $tableName = 'message_reply';

    /**
     * 获取消息列表
     * @param $info ($info['userid'] 用户ID)
     * @return mixed
     */
    public function get_messList($info)
    {
        switch ($info['opt']) {
            case 'get_mess_interlocution':
                $now = time();
                $time = strtotime('-2 day', $now);
                $map['a.to_uid'] = $info['userid'];
                $map['a.addtime'] = ['EGT', $time];
                $request['replay'] = D('MessageReply')
                    ->field('a.id,a.addtime,a.askid,a.isread,b.content,b.catid,c.mobile,d.truename,d.avatar')
                    ->alias('a')
                    ->join('LEFT JOIN destoon_appknow_question_ask AS b ON b.id = a.askid')
                    ->join('LEFT JOIN destoon_ucenter_member AS c ON c.userid = a.from_uid')
                    ->join('LEFT JOIN destoon_appknow_member_profile AS d ON d.userid = c.userid')
                    ->where($map)
                    ->order('a.addtime desc')
                    ->select();
                $request['invite'] = D('MessageInvite')
                    ->field('a.id,a.addtime,a.askid,a.isread,b.content,b.catid,c.mobile,d.truename,d.avatar')
                    ->alias('a')
                    ->join('LEFT JOIN destoon_appknow_question_ask AS b ON b.id = a.askid')
                    ->join('LEFT JOIN destoon_ucenter_member AS c ON c.userid = a.from_uid')
                    ->join('LEFT JOIN destoon_appknow_member_profile AS d ON d.userid = c.userid')
                    ->where($map)
                    ->order('a.addtime desc')
                    ->select();
                $replay_map['model'] = 'replay';
                array_walk($request['replay'], function (&$v, $k, $p) {
                    $v = array_merge($v, $p);
                }, $replay_map);
                $invite_map['model'] = 'invite';
                array_walk($request['invite'], function (&$v, $k, $p) {
                    $v = array_merge($v, $p);
                }, $invite_map);
                $data = array_merge($request['replay'], $request['invite']);
                break;
            // 用户关注消息
            case 'get_mess_attention':
                $now = time();
                $time = strtotime('-2 day', $now);
                $map['a.to_uid'] = $info['userid'];
                $map['a.addtime'] = ['EGT', $time];
                $request = D('MessageAttention')
                    ->field('a.id,a.addtime,a.isread,b.mobile,c.truename,c.avatar')
                    ->alias('a')
                    ->join('LEFT JOIN destoon_ucenter_member AS b ON b.userid = a.from_uid')
                    ->join('LEFT JOIN destoon_appknow_member_profile AS c ON c.userid = b.userid')
                    ->where($map)
                    ->order('a.addtime desc')
                    ->select();
                $replay_map['model'] = 'replay';
                array_walk($request['replay'], function (&$v, $k, $p) {
                    $v = array_merge($v, $p);
                }, $replay_map);
                $data = array_merge($request['sys'], $request['agree']);
                break;
            case 'get_mess_sys': //系统消息
                $now = time();
                $time = strtotime('-2 day', $now);
                $request['sys'] = D('MessageSys')
                    ->where("to_uid = " . $info['userid'] . " OR to_uid = 0 AND addtime >= $time")
                    ->field('id,content,isread,addtime')
                    ->order('addtime desc')
                    ->select();
                $request['agree'] = D('MessageAgree')
                    ->field('a.id,a.addtime,a.isread,b.content,b.askid,c.mobile,d.truename,d.avatar')
                    ->alias('a')
                    ->join('LEFT JOIN destoon_appknow_question_answer AS b ON b.id = a.answer_id')
                    ->join('LEFT JOIN destoon_ucenter_member AS c ON c.userid = a.from_uid')
                    ->join('LEFT JOIN destoon_appknow_member_profile AS d ON d.userid = c.userid')
                    ->where(array('a.to_uid' => $info['userid'], 'a.addtime' => ['EGT', $time]))
                    ->order('a.addtime desc')
                    ->select();
                $replay_map['truename'] = '系统管理';
                array_walk($request['sys'], function (&$v, $k, $p) {
                    $v = array_merge($v, $p);
                }, $replay_map);
                $replay_map['avatar'] = 'Uploads/avatar/user_system.png';
                array_walk($request['sys'], function (&$v, $k, $p) {
                    $v = array_merge($v, $p);
                }, $replay_map);
                $replay_map['model'] = 'sys';
                array_walk($request['sys'], function (&$v, $k, $p) {
                    $v = array_merge($v, $p);
                }, $replay_map);

                $invite_map['model'] = 'agree';
                array_walk($request['agree'], function (&$v, $k, $p) {
                    $v = array_merge($v, $p);
                }, $invite_map);
                $data = array_merge($request['sys'], $request['agree']);
                break;
            default:
                break;
        }
        foreach ($data as $k => $v) {
            $data[$k]['addtime'] = date("Y-m-d", $v['addtime']);
        }
        return $data;
    }

    /**
     * 判断是否已经阅读
     * @param $info ($info['opt'])  操作类型
     * @return int
     */
    public function get_mess_status($info)
    {

        switch ($info['opt']) {
            case 'get_mess_tips':      //通知状态
                $result = $this->get_mess_table('MessageReply', $info['id']);
                break;
            case 'get_mess_invite':    //邀请状态
                $result = $this->get_mess_table('MessageInvite', $info['id']);
                break;
            case 'get_mess_agree':     //点赞状态
                $result = $this->get_mess_table('MessageAgree', $info['id']);
                break;
            case 'get_mess_attention': //关注状态
                $result = $this->get_mess_table('MessageAttention', $info['id']);
                break;
            case 'get_mess_sys':       //系统消息状态
                $result = $this->get_mess_table('MessageSys', $info['id']);
                break;
            default:
                return 101;
                break;
        }
        if ($result) {
            return 200;
        } else {
            return 220;
        }
    }

    /**
     * 获取消息状态通用方法
     * @param $table [操作数据表]
     * @param $id [消息ID]
     * @return array|bool
     */
    public function get_mess_table($table, $id)
    {
        $data['isread'] = 1;
        $request = D($table)->where(array('id' => $id))->save($data);
        return $request;
    }

    /**
     * 保存回答消息
     * @param $info
     */
    public function add_message_reply($info)
    {
        $member_profile_model = new MemberProfileModel();
        $ask_model = new AskModel();
        $to_uid = !empty($info['uid']) ? $info['uid'] : $ask_model->get_uid($info['uid']);
        $data['from_uid'] = $info['uid'];
        $data['to_uid'] = $to_uid;
        $data['askid'] = $info['askid'];
        $data['addtime'] = time();
        $result = $this->add($data);
        if ($result) {
            $name = $member_profile_model->get_uid_by_name($data['to_uid']);
            Tools::Jpush_Send($data['to_uid'], $name . $this->mess_type['reply']);  //极光推送（回复消息）
        }
    }

    /**
     * 我的专家邀请列表
     * @param int $uid 用户id
     * @param int $start 开始数量
     * @param int $limit 结束数量
     * @return mixed
     */
    public function get_my_invite_expert_list($uid, $start, $limit)
    {
        $map['a.from_uid'] = $uid;
        $request = D('MessageInvite')
            ->field('a.addtime,a.isread,b.name,c.avatar,d.id,d.content,d.catid')
            ->alias('a')
            ->join('LEFT JOIN destoon_appknow_expert_profile AS b ON b.userid = a.to_uid')
            ->join('LEFT JOIN destoon_appknow_member_profile AS c ON c.userid = b.userid')
            ->join('LEFT JOIN destoon_appknow_question_ask AS d ON d.id = a.askid')
            ->limit($start, $limit)
            ->where($map)
            ->order('addtime desc')
            ->select();
        foreach ($request AS $k => $v) {
            $my_invite_expert_list[$k]['addtime'] = date('Y-m-d', $v['addtime']);
        }
        return $request;
    }

    /**
     * 添加点赞消息
     * @param $from_uid
     * @param $to_uid
     * @param $answer_id
     */
    public function add_message_agree($from_uid, $to_uid, $answer_id)
    {
        $member_profile_model = new MemberProfileModel();
        $data['from_uid'] = $from_uid;
        $data['to_uid'] = $to_uid;
        $data['answer_id'] = $answer_id;
        $data['addtime'] = time();
        $data['isread'] = 0;
        $result = M('message_agree')->add($data);
        if ($result) {
            $name = $member_profile_model->get_uid_by_name($from_uid);
            Tools::Jpush_Send($to_uid, $name . C('MESS_TYPE')['agree']);  //极光推送（回复消息）
        }
    }

    /**
     * 检查是否已经邀请过专家
     * @param $info
     * @return int
     */
    function check_invite_expert($info)
    {
        $map['uid'] = $info['invitation_uid'];
        $map['to_uid'] = $info['invite_uid'];
        $map['askid'] = $info['ask_id'];
        $result = M('message_invite')->where($map)->count(1);
        if ($result[0]['tp_count'] > 0) {
            return 217;
        } else {
            return 200;
        }
    }

    /**
     * 添加邀请专家
     * @param $info
     * @return mixed
     */
    function addInviteExpert($info)
    {
        //判断是否重复邀请
        if ($this->check_invite_expert($info) == 217) {
            $result['code'] = 201;
            $result['msg'] = C('STATUS')['217'];
            $result['result'] = false;
        } else {
            $data['from_uid'] = $info['invitation_uid'];
            $data['to_uid'] = $info['invite_uid'];
            $data['askid'] = $info['ask_id'];
            $data['addtime'] = time();
            try {
                $request = M('message_invite')->add($data);
                if (!$request) {
                    throw new Exception();
                } else {
                    $member_profile_model = new MemberProfileModel();
                    $name = $member_profile_model->get_uid_by_name($info['from_uid']);
                    Tools::Jpush_Send($info['to_uid'], $name . C('MESS_TYPE')['apply']);  //极光推送（邀请专家消息）
                    $result['code'] = 200;
                    $result['msg'] = C('STATUS')['200'];
                    $result['result'] = true;
                }
            } catch (Exception $exception) {
                $result['code'] = 400;
                $result['msg'] = C('STATUS')['101'];
                $result['result'] = false;
            }
        }
        return $result;
    }
}